// pages/goods-detail/index.js
// 点击轮播图 预览大图
//   1.给轮播图绑定事件
//   2.调用小程序api  wx.previewImage
/*
商品收藏
  1.页面onshow  的时候 加载缓存中的商品收藏的数据
  2.判断当前商品是不是被收藏
  3.点击收藏按钮
    1.判断改商品是否存在与缓存数组中
    2.已经存在 把该商品删除
    3.没有存在 把商品添加到收藏数组 同时存入缓存

*/
import { request } from "../../request/index.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    isCollect: false
  },
  GoodsInfo: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    var curPages = getCurrentPages();
    let pages = curPages[curPages.length - 1]
    let options = pages.options
    const { goods_id } = options
    this.getGoodsDetail(goods_id)

  },
  //获取商品详情4
  async getGoodsDetail(goods_id) {
    const goodsObj = await request({ url: '/goods/detail', data: { goods_id } })
    this.GoodsInfo = goodsObj
    //获取缓存中商品收藏数组
    let collect = wx.getStorageSync("collect") || [];
    let isCollect = collect.some(v => v.goods_id === this.GoodsInfo.goods_id)
    this.setData({
      goodsObj: {
        goods_name: goodsObj.goods_name,
        goods_price: goodsObj.goods_price,
        //iphone部分手机不识别webp图片格式
        //后台改
        //临时自己该（后台存在，webp=jpg)
        goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, ".jpg"),
        pics: goodsObj.pics
      },
      isCollect
    })
  },
  //点击轮播图放大预览
  handlePrevewImage(e) {
    const urls = this.GoodsInfo.pics.map((item) => item.pics_mid)
    // const urls = this.data.goodsObj.pics.map((item) => item.pics_mid)
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      urls,
      current,
    })
  },
  //点击加入购物车
  handleCartAdd() {
    //1.获取缓存中的购物车数组
    let cart = wx.getStorageSync('cart') || [];
    //2.判断商品是否在购物车数据中
    let index = cart.findIndex(item => item.goods_id === this.GoodsInfo.goods_id)
    if (index === -1) {
      //不存在 第一次添加
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo);
    } else {
      //存在 num++
      console.log(cart[index].num)
      cart[index].num++;
    }
    //把购物车重新加入缓存
    wx.setStorageSync('cart', cart);
    wx.showToast({
      title: '加入成功',
      icon: 'success',
      mask: true, //防止用户手抖
    })
  },
  //点击商品收藏图标
  handleCollect(){
    let isCollect=false
   let collect= wx.getStorageSync("collect")||[];
   let index=collect.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id)
   if(index!==-1){
     //能找到，已经收藏  在数组中删除
     collect.splice(index,1)
     isCollect=false
     wx.showToast({
       title: '取消收藏',
       icon: 'success',
       mask: true,
     });
   }else{
     collect.push(this.GoodsInfo)
     isCollect=true
     wx.showToast({
      title: '收藏成功',
      icon: 'success',
      mask: true,
    });
   }
   wx.setStorageSync("collect", collect);
   this.setData({
     isCollect,
     isCollect
   })
  }
})